package org.tong.modulejwt.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.tong.common.utils.Response;
import org.tong.modulejwt.utils.JwtTokenHelper;
import org.tong.modulejwt.utils.ResultUtil;
import org.tong.modulejwt.vo.LoginRespVO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证成功处理
 */
@Component
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    JwtTokenHelper jwtTokenHelper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails userDetails = (UserDetails)authentication.getPrincipal();
        String username = userDetails.getUsername();
        String token = jwtTokenHelper.generateToken(username);
        LoginRespVO loginRespVO = new LoginRespVO();
        loginRespVO.setToken(token);
        ResultUtil.ok(response, Response.success(loginRespVO));
    }
}
